﻿using Dm.filter.rw;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X509.Qualified;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Model.DbContext;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace SmartPlant.Services
{
    /// <summary>
    /// 操作完之后，要重新查询一次 系统里的codelist
    /// </summary>
    public class CodeListService : BaseService, ICodeListService
    {
        public CodeListService()
        {
        }
        /// <summary>
        /// 增加一个下拉到lookup表。
        /// </summary>
        /// <param name="type"></param>
        /// <param name="NewItem"></param>
        /// <returns></returns>
        public async Task<bool> UpdateCodelist(string type, DropDownListObj NewItem, bool refresh = false)
        {
            switch (type)
            {
                case nameof(ComponentLocation):
                    string uri = $"/api/Project/{GlobalObject.CurrentProject.ProjId}/component-location-api";
                    var existObj = new ComponentLocation() { CmpntLocId = Convert.ToDecimal(NewItem.Id), CmpntLocName = NewItem.Name, CmpntLocDesc = NewItem.Desc, PlantId = GlobalObject.CurrentUnit.PlantId };
                    var data = await PutBodyAsync<bool, ComponentLocation>(uri, existObj);

                    if (data.data == true && refresh)
                    {
                        await this.GetDropDownListByDefAsync(GlobalObject.lookupDic[nameof(ComponentLocation)], "lookup", true);

                    }

                    return data.data;
                default:
                    return false;
            }
        }

        /// <summary>
        /// 删一个lookup表里的下拉。之后会重新查一下
        /// </summary>
        /// <param name="type">nameof(某个类定义)</param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<bool> DelCodelist(string type, string Id)
        {
            switch (type)
            {
                case nameof(ComponentLocation):
                    string uri = $"/api/Project/{GlobalObject.CurrentProject.ProjId}/component-location-api/{Id}";
                    var data = await DeleteAsync<bool>(uri);

                    if (data.data == true)
                    {
                        await this.GetDropDownListByDefAsync(GlobalObject.lookupDic[nameof(ComponentLocation)], "lookup", true);

                    }
                    return data.data;


                default:
                    return false;
            }
        }
        /// <summary>
        /// 错误示范。不能直接用同步的方法去调用异步的http请求
        /// </summary>
        /// <param name="type"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        [Obsolete("错误示范")]
        public bool DelCodelist2(string type, string Id)
        {
            switch (type)
            {
                case nameof(ComponentLocation):
                    string uri = $"/api/Project/{GlobalObject.CurrentProject.ProjId}/component-location-api/{Id}";
                    var data = DeleteAsync<bool>(uri).Result;
                    return data.data;


                default:
                    return false;
            }
        }
        public async Task<bool> AddCodeList(string type, DropDownListObj NewItem, bool refresh = false)
        {
            switch (type)
            {
                case nameof(ComponentLocation):
                    string uri = $"/api/Project/{GlobalObject.CurrentProject.ProjId}/component-location-api/{false}";
                    var newObj = new ComponentLocation() { CmpntLocId = 0, CmpntLocName = NewItem.Name, CmpntLocDesc = NewItem.Desc, PlantId = GlobalObject.CurrentUnit.PlantId };
                    var data = await PostBodyAsync<ComponentLocation, ComponentLocation>(uri, newObj);
                    //有个bug，这个请求后，调试不会进行下去了。
                    if (refresh)
                    {
                        await this.GetDropDownListByDefAsync(GlobalObject.lookupDic[nameof(ComponentLocation)], "lookup", refresh);
                    }


                    return true;


                default:
                    return false;
            }


        }


        /// <summary>
        /// 会用到的下拉列表集合
        /// </summary>
        public static List<DropDownLists> DropDownListsAll = new List<DropDownLists>();
        /// <summary>
        /// 查询某个下拉列表
        /// </summary>
        /// <param name="ProjId"></param>
        /// <param name="itemattributionid"></param>
        /// <param name="refresh">true时，会重新查询一次，然后覆盖</param>
        /// <returns></returns>
        public async Task<List<DropDownListObj>> GetDropDownListByDefAsync(string ATTRIBUTE_DATATYPE, string type = "lookup", bool refresh = false)
        {
            var res2 = DropDownListsAll.FirstOrDefault(x => x.ATTRIBUTE_DATATYPE == ATTRIBUTE_DATATYPE);
            var ProjId = GlobalObject.CurrentProject.ProjId;
            if (res2 == null)
            {
                //没有

                string uri = "";
                if (type == "lookup")
                {
                    uri = $"/api/Project/{ProjId}/codelists-api/drop-down-list-by-def/{ATTRIBUTE_DATATYPE}/lookup";
                }
                else if (type == "enum")
                {
                    uri = $"/api/Project/{ProjId}/codelists-api/drop-down-list-by-def/{ATTRIBUTE_DATATYPE}/enum";
                }
                var res = await GetAsync<List<DropDownListObj>>(uri);//server端暂时只给id和name

                DropDownListsAll.Add(new DropDownLists()
                {
                    ATTRIBUTE_DATATYPE = ATTRIBUTE_DATATYPE,
                    type = type,
                    DropDownList = res.data
                });
                return res.data;
            }
            else
            {
                //有
                if (refresh)
                {
                    //需要

                    string uri = "";
                    if (type == "lookup")
                    {
                        uri = $"/api/Project/{ProjId}/codelists-api/drop-down-list-by-def/{ATTRIBUTE_DATATYPE}/lookup";
                    }
                    else if (type == "enum")
                    {
                        uri = $"/api/Project/{ProjId}/codelists-api/drop-down-list-by-def/{ATTRIBUTE_DATATYPE}/enum";
                    }
                    var res = await GetAsync<List<DropDownListObj>>(uri);//server端暂时只给id和name
                    DropDownListsAll.Remove(res2);
                    DropDownListsAll.Add(new DropDownLists()
                    {
                        ATTRIBUTE_DATATYPE = ATTRIBUTE_DATATYPE,
                        type = type,
                        DropDownList = res.data
                    });
                    return res.data;
                }
                else
                {
                    //不需要
                    return res2.DropDownList;
                }



            }



        }

        /// <summary>
        /// 查询某个下拉列表
        /// </summary> 
        /// <param name="itemattributionid"></param> 
        /// <returns></returns>
        public async Task<List<DropDownListObj>> GetDropDownListByAttrAsync(decimal itemattributionid)
        {
            var itemAttr = await new SysServiceInit().GetItemAttr(GlobalObject.CurrentProject.ProjId.ToString(), itemattributionid);
            if (itemAttr == null)
            {
                return null;
            }
            var key = itemAttr.Attribution.Attribute.AttributeDatatype;
            var type = itemAttr.Attribution.Attribute.convertedDataType;
            if (key == "L1542")
            {
                var uomId = itemAttr.Attribution.Attribute.AttributeUomid;
                var res = new List<DropDownListObj>();
                if (uomId != 1007)
                {
                    var col = GlobalObject.UnitOfMeasureCollection.Where(x => x.UoM_TYPE_ID == uomId);

                    foreach (var uom in col)
                    {
                        res.Add(new DropDownListObj() { Id = uom.UomId.ToString(), Name = uom.UomCode });
                    }
                }
                else
                {
                    //1007 代表所有uom都可以选
                    foreach (var uom in GlobalObject.UnitOfMeasureCollection)
                    {
                        res.Add(new DropDownListObj() { Id = uom.UomId.ToString(), Name = uom.UomCode });
                    }


                }
                return res;
            }

            if (itemAttr.Path.StartsWith("-"))
            {
                //需要特殊过滤的
                string uri = $"/api/Project/{GlobalObject.CurrentProject.ProjId}/codelists-api/drop-down-list/{itemattributionid}";
                var res = await GetAsync<List<DropDownListObj>>(uri);//server端暂时只给id和name
                return res.data;
            };

            var existObj = DropDownListsAll.FirstOrDefault(x => x.ATTRIBUTE_DATATYPE == key);

            if (existObj == null)
            {
                //没有
                string uri = $"/api/Project/{GlobalObject.CurrentProject.ProjId}/codelists-api/drop-down-list/{itemattributionid}";
                var res = await GetAsync<List<DropDownListObj>>(uri);//server端暂时只给id和name


                DropDownListsAll.Add(new DropDownLists()
                {
                    type = type,
                    ATTRIBUTE_DATATYPE = key,
                    DropDownList = res.data
                });
                return res.data;
            }
            else
            {
                //有

                //不需要
                return existObj.DropDownList;


            }



        }
        /// <summary>
        /// 目前只在初始化时运行一次。如果已有，会默认覆盖
        /// </summary>
        /// <param name="ProjId"></param>
        /// <param name="ItemAttributionIds"></param>
        /// <returns></returns>
        public async Task<List<List<DropDownListObj>>> GetDropDownListsByAttrAsync(string ProjId, List<string> ItemAttributionIds)
        {
            string uri = $"/api/Project/{ProjId}/codelists-api/drop-down-lists";
            var data = await PostBodyAsync<List<List<DropDownListObj>>, string>(uri, string.Join(',', ItemAttributionIds));//从服务器查询新的下拉

            for (int i = 0; i < ItemAttributionIds.Count; i++)
            {
                var itemAttr = await new SysServiceInit().GetItemAttr(ProjId, Convert.ToDecimal(ItemAttributionIds[i]));
                if (itemAttr != null)
                {
                    if (itemAttr.Attribution.Attribute.AttributeDatatype != "L1542")
                    {
                        var existObj = DropDownListsAll.FirstOrDefault(x => x.ATTRIBUTE_DATATYPE == itemAttr.Attribution.Attribute.AttributeDatatype);
                        if (existObj != null)
                        {
                            DropDownListsAll.Remove(existObj);//remove先
                        }
                        DropDownListsAll.Add(new DropDownLists()
                        {
                            type = itemAttr.Attribution.Attribute.convertedDataType, //enum,lookup,
                            ATTRIBUTE_DATATYPE = itemAttr.Attribution.Attribute.AttributeDatatype,//如L1084,E2032,
                            DropDownList = data.data[i]
                        });
                    }

                }

            }
            return data.data;
        }




    }
}
